package com.scalar.chiptrack.adaptor.wipfed;


import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.TestLot;
import com.scalar.chiptrack.adaptor.AssemblyLot;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.CSVParserImpl;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.FabSortAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.adaptor.dao.NewAdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Locale;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Date;

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import jxl.Workbook;
import jxl.Sheet;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;


/**
 * User: ChandraSekhar
 * Date: Aug 6, 2007
 * Time: 3:46:54 PM
 */
public class WipFedSLIParser extends JobHandler implements AdaptorConstants
{
    HashMap m_fabDataMap        = new HashMap();
    HashMap m_fabOptionDataMap  = new HashMap();
    HashMap m_waferStoreDataMap = new HashMap();
    HashMap m_dieBankDataMap    = new HashMap();
    HashMap m_assemblyDataMap   = new HashMap();
    HashMap m_ftDataMap         = new HashMap();
    HashMap m_fpoDataMap        = new HashMap();
    HashMap m_trDataMap         = new HashMap();
    HashMap m_fgDataMap         = new HashMap();
    HashMap m_tsmcMap           = new HashMap();
    HashMap m_osetMap           = new HashMap();
    HashMap m_fabShipDataMap    = new HashMap();

    ArrayList charteredFabList  = new ArrayList();
    ArrayList tsmcFabList       = new ArrayList();
    ArrayList osetAsssemblyList = new ArrayList();

    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    DBTransaction dbTransaction         = null;

    public WipFedSLIParser() throws Exception
    {
        try
        {
            m_dataOutputDir = ConfigManager.getWipFedSheetDirectory();
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir, "WIPFED" );

            FabSortAdaptorDAO.setLogger(m_parserLogger);
            /*AssemblyAdaptorDAO.setLogger(m_parserLogger);
            TestAdaptorDAO.setLogger(m_parserLogger);
            InventoryLotDAO.setLogger(m_parserLogger);*/
            ShippedLotDAO.setLogger( m_parserLogger);

            AdaptorUtils.setLogger( m_parserLogger);
        }
        catch (ScalarException e)
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading WIPFED output directory details from database, Exception: " + e );
            throw e;
        }
    }

    public static void main(String args[]) throws Exception
    {
        new WipFedSLIParser().execute();
    }


    public void execute() throws Exception
    {

        AdaptorUtils.printHeader("WIPFED SLI", CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done");

        File wipDataoutDir = new File(m_dataOutputDir);

        File[] fileList = wipDataoutDir.listFiles();

        if ((fileList == null) || (fileList.length <= 3))
        {
            log("No file found in directory: " + wipDataoutDir);
            throw new ScalarException("No file found in directory: " + wipDataoutDir + "----\n\n");
        }

        ArrayList successFileList   = new ArrayList();
        boolean success             = false;

        //PARSING STARTS FROM HERE
        for (int i = 0; i < fileList.length; i++)
        {
            if (fileList[i].isDirectory() == true)
            {
                continue;
            }

           /* if ( (fileList[i].getName() != null) && fileList[i].getName().trim().startsWith( WipFedAdaptor.FILE_NAME_SLI_WIP_STATUS ) )
            {
                if (  fileList[i].getName().trim().endsWith(".xls") )
                {
                    ArrayList m_wipStatusList = parsewipfedInfosheet( fileList[i].getAbsolutePath() );

                    if ( m_wipStatusList != null && m_wipStatusList.size() > 0)
                    {
                        getWipFedDetails( m_wipStatusList );
                    }
                }
                successFileList.add( fileList[i] );
            }*/

            if ( (fileList[i].getName() != null) && fileList[i].getName().trim().startsWith( WipFedAdaptor.FILE_NAME_SHIP_STATUS ) )
            {

                ArrayList m_shipStatusList = parseShipmentReport( fileList[i].getAbsolutePath() );

                if ( m_shipStatusList != null && m_shipStatusList.size() > 0)
                {
                    getShippingDetails( m_shipStatusList );
                }

                successFileList.add( fileList[i] );
            }
            if ( (fileList[i].getName() != null) && fileList[i].getName().trim().startsWith( WipFedAdaptor.FILE_NAME_CYPRESS_WIP ) )
            {

                parseDailyWipReport( fileList[i].getAbsolutePath() );

                successFileList.add( fileList[i] );
            }
        }

         /*Updating the Chartered Fab Lot Information*/
        /*try
        {
            // Step 1
            // Save Fab Information
            if ( charteredFabList != null && charteredFabList.size() > 0 )
            {
               log( " Updating Wip Fed Chartered Fab Lot Information" );
               CharteredDAO.saveWipFedCharteredDetails( dbTransaction, charteredFabList );

               charteredFabList.clear();
               charteredFabList = null;
            }
            success = true;
        }
        catch ( ScalarException se )
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Fab Lot information into database: " + se );
            throw se;
        }*/

        /*Updating the TSMCFab Lot Information*/
        /*try
        {
            // Step 1
            // Save Fab Information
            if ( tsmcFabList != null && tsmcFabList.size() > 0 )
            {
               log( " Updating Wip Fed TSMC Fab Lot Information" );
              TSMCDAO.saveWipFedTSMCDetails( dbTransaction, tsmcFabList);
              tsmcFabList.clear();
              tsmcFabList = null;
            }
            success = true;
        }
        catch ( ScalarException se )
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Fab Lot information into database: " + se );
            throw se;
        }*/

        /*Updating the Fab Lot Information*/
        try
        {
            // Step 1
            // Save Fab Information
            if ( m_fabDataMap.isEmpty() == false )
            {
               log( " Updating Fab Lot Information" );
               FabSortAdaptorDAO.saveFabLot( dbTransaction, m_fabDataMap.values().iterator(), LOCATION_TYPE_FAB, null ) ;
            }
            else
            {
                FabSortAdaptorDAO.closeFabSortLot( dbTransaction, LOCATION_TYPE_FAB, null );
            }
            m_fabDataMap.clear();
            m_fabDataMap = null;

            if ( m_fabShipDataMap.isEmpty() == false )
            {
                log( " Updating Fab Shipping Lot Information" );
                ShippedLotDAO.saveShippedLot( dbTransaction, m_fabShipDataMap.values().iterator() );
            }
            success = true;
        }
        catch ( ScalarException se )
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Fab Lot information into database: " + se );
            throw se;
        }

        /*try
        {
            // Step 1
            // Save Fab Information
            if ( m_fabOptionDataMap.isEmpty() == false )
            {
               log( " Updating Fab Lot Information" );
               FabSortAdaptorDAO.saveFabLot( dbTransaction, m_fabOptionDataMap.values().iterator(), LOCATION_TYPE_FAB_OPTION, null ) ;
            }
            else
            {
                FabSortAdaptorDAO.closeFabSortLot( dbTransaction, LOCATION_TYPE_FAB_OPTION, null );
            }
            m_fabOptionDataMap.clear();
            m_fabOptionDataMap = null;
            success = true;
        }
        catch ( ScalarException se )
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Fab Lot information into database: " + se );
            throw se;
        }*/
        /* Updating lots from Wip fed and Chartered */
       /* try
        {
            HashMap m_charteredMap =CharteredDAO.getCharteredFabList();
            if ( m_charteredMap.isEmpty() == false )
            {
                ArrayList charteredList = new ArrayList();
                charteredList.addAll( m_charteredMap.values() );
                log( " Updating Wip Fed Chartered Fab Lot Information in to  Fab lot Table" );
                FabSortAdaptorDAO.saveFabLot( null, charteredList, VENDOR_NAME_CHARTERED );

                charteredList.clear();
                charteredList = null;
            }
            m_charteredMap.clear();
            m_charteredMap = null;

            success = true;
        }
        catch( Exception e)
        {
            success = false;
            e.printStackTrace();
            throw e;
        }*/

        /* Updating lots from Wip fed and Chartered */
      /* try
        {
            m_tsmcMap = TSMCDAO.getTSMCFabList();
            ArrayList tsmcList = new ArrayList();
            tsmcList.addAll( m_tsmcMap.values() );
            log( " Updating Wip Fed TSMC Fab Lot Information in to  Fab lot Table" );
            FabSortAdaptorDAO.saveFabLot( null, tsmcList, VENDOR_NAME_TSMC );
            m_tsmcMap.clear();
            m_tsmcMap = null;
        }
        catch( Exception e)
        {
            success = false;
            e.printStackTrace();
        }*/

        /*Updating the Die Bank Lot Information*/
       /* try
        {
            // Save Die Bank Information
            if( m_waferStoreDataMap.isEmpty() == false )
            {
                log(" Updating Wafer Store Lot Information");
                InventoryLotDAO.saveInventoryLot( dbTransaction, m_waferStoreDataMap.values().iterator(), INVENTORY_TYPE_WAFER_STORE, null );
            }
            else
            {
                InventoryLotDAO.closeInventoryLot( dbTransaction, INVENTORY_TYPE_WAFER_STORE, null);
            }
            m_waferStoreDataMap.clear();
            m_waferStoreDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Die Bank Lot information into database: " + se);
            throw se;
        }*/

        /*Updating the Die Bank Lot Information
        try
        {
            // Save Die Bank Information
            if( m_dieBankDataMap.isEmpty() == false )
            {
                log(" Updating Die Bank Lot Information");
                InventoryLotDAO.saveInventoryLot( dbTransaction, m_dieBankDataMap.values().iterator(), INVENTORY_TYPE_DIE_BANK, null );
            }
            else
            {
                InventoryLotDAO.closeInventoryLot( dbTransaction, INVENTORY_TYPE_DIE_BANK, null);
            }
            m_dieBankDataMap.clear();
            m_dieBankDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Die Bank Lot information into database: " + se);
            throw se;
        }*/

        /*Updating the Assembly Lot Information
        try
        {
            // Step 3
            // Save Assembly Information
            if( osetAsssemblyList.isEmpty() == false )
            {
                log(" Updating OSET Assembly Lot Information in to Intermediate table");
                OSETDAO.saveWipFedOSETDetails( null, osetAsssemblyList, false );
            }
            else
            {
                OSETDAO.saveWipFedOSETDetails( null, osetAsssemblyList, true );
            }
            osetAsssemblyList.clear();
            osetAsssemblyList = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Assembly Lot information into Intermediate tables: " + se);
            throw se;
        }*/

        /*Updating the Assembly Lot Information
        try
        {
            // Save Assembly Information
            if( m_assemblyDataMap.isEmpty() == false )
            {
                log(" Updating Assembly Lot Information");
                AssemblyAdaptorDAO.saveAssemblyLot( dbTransaction, m_assemblyDataMap.values().iterator(), WIP_TYPE_ASSEMBLY, null );
            }
            else
            {
                AssemblyAdaptorDAO.closeAssemblyLot( dbTransaction, WIP_TYPE_ASSEMBLY, null );
            }
            m_assemblyDataMap.clear();
            m_assemblyDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Assembly Lot information into database: " + se);
            throw se;
        }*/


        /* Updating lots from Wip fed and Chartered 
       try
        {
            m_osetMap = OSETDAO.getOSETAssemblyMap();
            log( " Updating OSET Assembly information from Wip Fed and OSET " );
            AssemblyAdaptorDAO.saveAssemblyLot( null, m_osetMap.values().iterator(), WIP_TYPE_ASSEMBLY, VENDOR_NAME_OSET );
            m_osetMap.clear();
            m_osetMap = null;
        }
        catch( Exception e)
        {
            success = false;
            e.printStackTrace();
        }
	*/
         /*Updating the FT Test Lot Information
        try
        {
            // Save FT Test Information
            if( m_ftDataMap.isEmpty() == false )
            {
                log(" Updating Test Lot Information");
                TestAdaptorDAO.saveTestLot( dbTransaction,  m_ftDataMap.values().iterator(),LOCATION_TYPE_FT,  null );

            }
            else
            {
                TestAdaptorDAO.closeTestLot( dbTransaction, LOCATION_TYPE_FT, null);
            }
            m_ftDataMap.clear();
            m_ftDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update FT Test Lot information into database: " + se);
            throw se;
        }*/

         /*Updating the FPO Test Lot Information
        try
        {
            // Save FPO Test Information
            if( m_fpoDataMap.isEmpty() == false )
            {
                log(" Updating Test Lot Information");
                TestAdaptorDAO.saveTestLot( dbTransaction,  m_fpoDataMap.values().iterator(),LOCATION_TYPE_FPO,  null );

            }
            else
            {
                TestAdaptorDAO.closeTestLot( dbTransaction, LOCATION_TYPE_FPO, null);
            }
            m_fpoDataMap.clear();
            m_fpoDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Test Lot information into database: " + se);
            throw se;
        }*/
        /*Updating the Class Store Lot Information
        try
        {
            // Save Class Store Information
            if( m_trDataMap.isEmpty() == false )
            {
                log(" Updating Class Store Lot Information");
                InventoryLotDAO.saveInventoryLot( dbTransaction, m_trDataMap.values().iterator(), LOCATION_TYPE_TAPE_REEL, null );
            }
            else
            {
                InventoryLotDAO.closeInventoryLot( dbTransaction, LOCATION_TYPE_TAPE_REEL, null);
            }
            m_trDataMap.clear();
            m_trDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Class Store Lot information into database: " + se);
            throw se;
        }*/

        /*Updating the FG Lot Information
        try
        {
            // Step 2
            // Save Finished Goods Information
            if( m_fgDataMap.isEmpty() == false )
            {
                log(" Updating Finished Goods Lot Information");
                InventoryLotDAO.saveInventoryLot( dbTransaction, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, null );
            }
            else
            {
                InventoryLotDAO.closeInventoryLot( dbTransaction, LOCATION_TYPE_FG, null);
            }
            m_fgDataMap.clear();
            m_fgDataMap = null;
            success = true;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Finished Goods Lot information into database: " + se);
            throw se;
        }*/

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
       // AdaptorDAO.sendAllNotifications( VENDOR_NAME_CHARTERED, true, true, true);
        //AdaptorDAO.sendAllNotifications( VENDOR_NAME_TSMC , true, true, true);
        //AdaptorDAO.sendAllNotifications( VENDOR_NAME_ATP,   true, true, true );
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_CMI ,  true, true, true);
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_CML ,  true, true, true);
        AdaptorDAO.sendAllNotifications( VENDOR_NAME_CMT,   true, true, true );
        //AdaptorDAO.sendAllNotifications( VENDOR_NAME_ATK ,  true, true, true);
        //AdaptorDAO.sendAllNotifications( VENDOR_NAME_OSET,  true, true, true );

         // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots( VENDOR_NAME_CMI );
        //AdaptorDAO.closeDropOutLots( VENDOR_NAME_TSMC );
       // AdaptorDAO.closeDropOutLots( VENDOR_NAME_CHARTERED );
        AdaptorDAO.closeDropOutLots( VENDOR_NAME_CML );
        AdaptorDAO.closeDropOutLots( VENDOR_NAME_CMT );
       //AdaptorDAO.closeDropOutLots( VENDOR_NAME_ATK );
        //AdaptorDAO.closeDropOutLots( VENDOR_NAME_OSET );
        //AdaptorDAO.closeDropOutLots( VENDOR_NAME_ATP );

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( WipFedAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, WipFedAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, WipFedAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
    }//end of execute method

    /**
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList parsewipfedInfosheet(String fileName) throws Exception
    {
        if ( fileName == null )
        {
            throw new ScalarException( "Filename argument is null" );
        }

        WipFedStatus wipFedStatus       = null;
        ArrayList wipfedList                  = new ArrayList();

        try
        {
            File wipFedFile = new File( fileName );
            if ( wipFedFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "Parsing the file for SLI Wip Fed Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "Parsing the file for SLI Wip Fed Report..." );

            Workbook workbook = Workbook.getWorkbook( wipFedFile );
            Sheet sheet = workbook.getSheet( 1 );

            Cell[] row = null;

            for ( int rowCount = 3; rowCount < sheet.getRows(); rowCount++ )
            {
                row = sheet.getRow( rowCount );

                wipFedStatus = new WipFedStatus();

                if( row.length > 0 )
                {
                    if ( row[0].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setMfgArea( null );
                    }
                    else
                    {
                        wipFedStatus.setMfgArea( row[0].getContents().trim() );
                    }

                }
                if( row.length > 1)
                {
                    if ( row[1].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setMfgLoc( null );
                    }
                    else
                    {
                        wipFedStatus.setMfgLoc( row[1].getContents().trim() ) ;
                    }
                }
                if( row.length > 2)
                {
                    if ( row[2].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setStep( null );
                    }
                    else
                    {
                        wipFedStatus.setStep( row[2].getContents().trim() );
                    }
                }
                if( row.length > 3)
                {
                    if ( row[3].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setDevice( null );
                    }
                    else
                    {
                        wipFedStatus.setDevice( row[3].getContents().trim() );
                    }
                }

                if ( row.length > 4 )
                {
                   if ( row[4].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setPkg( null );
                    }
                    else
                    {
                        wipFedStatus.setPkg( row[4].getContents().trim() );
                    }
                }

                if ( row.length > 5 )
                {
                   if ( row[5].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setMktPart( null );
                    }
                    else
                    {
                        wipFedStatus.setMktPart( row[5].getContents().trim() );
                    }
                }
                if( row.length > 6 )
                {
                    if ( row[6].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setLotNumber( null );
                    }
                    else
                    {
                        wipFedStatus.setLotNumber( row[6].getContents().trim() );
                    }

                }
                if( row.length > 7 )
                {
                    if ( row[7].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setSplit( null );
                    }
                    else
                    {
                        wipFedStatus.setSplit( row[7].getContents().trim() );
                    }
                }
                if ( row.length > 8 )
                {
                    if ( row[8].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setStatus( null );
                    }
                    else
                    {
                        wipFedStatus.setStatus( row[8].getContents().trim() );
                    }
                }
                if( row.length > 9 )
                {
                    if (row[9].getType().equals(CellType.EMPTY))
                    {
                        wipFedStatus.setStartDate(null);
                    }
                    else if( row[9].getType().equals( CellType.DATE ) )
                    {
                        DateCell dc = (DateCell) row[9];
                        java.util.Date dateIn = null;
                        dateIn = dc.getDate();

                        if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                        {
                            Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "GMT" ), Locale.US );
                            cal.setTime(dateIn);
                            dateIn = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipFedStatus.setStartDate( StringUtils.formatDateToString( dateIn )  ) ;
                        }
                        else
                        {
                            Calendar cal = new GregorianCalendar();
                            cal.setTime(dateIn);
                            dateIn = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipFedStatus.setStartDate(StringUtils.formatDateToString(dateIn));
                        }
                    }
                }

                if( row.length > 10 )
                {
                    if (row[10].getType().equals(CellType.EMPTY))
                    {
                        wipFedStatus.setStartDate(null);
                    }
                    else if( row[10].getType().equals( CellType.DATE ) )
                    {
                        DateCell dc = (DateCell) row[10];
                        java.util.Date dateIn = null;
                        dateIn = dc.getDate();

                        if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                        {
                            Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "GMT" ), Locale.US );
                            cal.setTime(dateIn);
                            dateIn = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipFedStatus.setRsDate( StringUtils.formatDateToString( dateIn )  );
                        }
                        else
                        {
                            Calendar cal = new GregorianCalendar();
                            cal.setTime(dateIn);
                            dateIn = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                            wipFedStatus.setRsDate(StringUtils.formatDateToString(dateIn));
                        }
                    }
                }
                if( row.length > 11 )
                {
                    if ( row[11].getType().equals(CellType.EMPTY) )
                    {
                        wipFedStatus.setDieQty( null );
                    }
                    else
                    {
                        wipFedStatus.setDieQty( row[11].getContents().trim() );
                    }
                }

                if ( wipFedStatus.getLotNumber() != null  )
                {
                    wipfedList.add( wipFedStatus );
                }
            }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw ex;
        }

        return wipfedList;
    }

    private ArrayList parseShipmentReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ArrayList shipList              = new ArrayList();
        String line                     = null;

        try
        {
            File detailShipFile = new File( fileName );
            if ( detailShipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for Shipment Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Shipment Report..." );

            BufferedReader reader = new BufferedReader( new FileReader( detailShipFile ) );
            reader.readLine();  // Read out <Header Info > Line

            while ( ( line = reader.readLine() ) != null  && line.length() > 0 )
            {
                WipFedStatus shipStatus = new WipFedStatus();

                line = line.replaceAll( "\"", "" );
                String[] token = line.split( "," );

                for (int x = 0; x < token.length; x++)
                {
                    if (token[x] != null && token[x].trim().length() > 0 )
                    {
                        switch (x)
                        {
                            case 0:
                                    shipStatus.setDevice( token[x].trim() );
                                    break;
                            case 1:
                                    shipStatus.setLotNumber( token[x].trim() );
                                    break;
                            case 2:
                                    shipStatus.setShipQty( 1 +"" );
                                    break;
                            case 3:
                                    shipStatus.setWaferID( token[x].trim() );
                                    break;
                            case 4:
                                    shipStatus.setShipDate( token[x].trim().split(" ")[0] );
                                    break;
                            case 5:
                                    shipStatus.setNextMfgLoc(token[x].trim() );
                                    break;
                         }
                    }
                }

                shipList.add( shipStatus );
            }

            try
            {
                if ( reader != null )
                {
                   reader.close();
                }
            }
            catch(IOException ignore)
            {

            }
        }
        catch ( Exception ex )
        {   System.out.println("ERROR!!!ERROR!!! While Parsing the CMT Shipment Report");
            ex.printStackTrace();
            throw ex;
        }

        return shipList;

    } // end of prase Shipment Report method


    public void getWipFedDetails( ArrayList wipFedList ) throws Exception
    {

        String partNumber       = null;
        String mktPartNumber    = null;
        String lotNumber        = null;
        WipFedStatus wipStatus  = null;

        FabSortLot fabLot           = null;
        InventoryLot inventoryLot   = null;
        AssemblyLot assemblyLot     = null;
        TestLot     testLot         = null;

        try
        {
            Iterator wipFedIterator = wipFedList.iterator();

            while ( wipFedIterator.hasNext() )
            {
                wipStatus = (WipFedStatus) wipFedIterator.next();

                partNumber      = wipStatus.getDevice();
                mktPartNumber   = wipStatus.getMktPart();
                lotNumber       = wipStatus.getLotNo();

                /* Fab Lots*/
                if( wipStatus.getMfgArea() != null &&( "PRE_OPTION".equalsIgnoreCase( wipStatus.getMfgArea().trim() )
                        ||  "FAB".equalsIgnoreCase( wipStatus.getMfgArea().trim() ) || "WAFERSTORE".equalsIgnoreCase( wipStatus.getMfgArea().trim()) ) )
                {
                    String vendorName = null;

                    if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("Cypress Fab 2") )
                    {
                        vendorName = VENDOR_NAME_CMT;
                    }
                    else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("Cypress Fab 4") )
                    {
                        vendorName = VENDOR_NAME_CMI;
                    }
                   /* else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CSM") )
                    {
                        vendorName = VENDOR_NAME_CHARTERED;
                    }
                    else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("TSMC") )
                    {
                        vendorName = VENDOR_NAME_TSMC;
                    }*/
                    
                    if( partNumber != null && lotNumber != null && vendorName != null )
                    {
                        fabLot = ( FabSortLot) m_fabDataMap.get( lotNumber + partNumber + vendorName );

                        if( fabLot == null )
                        {
                            fabLot = new FabSortLot( vendorName, WIP_TYPE_FAB );
                            m_fabDataMap.put( lotNumber + partNumber + vendorName, fabLot );
                        }

                        int quantity = 0;
                        if( fabLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(fabLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch( NumberFormatException npe )
                            {
                            }
                        }
                        if( quantity > 0 && quantity <= 25)
                        {
                            wipStatus.setPsType( WIP_TYPE_FAB );
                            if ( VENDOR_NAME_CHARTERED.equalsIgnoreCase( vendorName ) )
                            {
                                wipStatus.setCharteredPartNo( partNumber );
                                wipStatus.setMesQty(wipStatus.getDieQty());
                                wipStatus.setMesStep(wipStatus.getStep());
                                charteredFabList.add( wipStatus );
                            }
                            else if ( VENDOR_NAME_TSMC.equalsIgnoreCase( vendorName ) )
                            {
                                wipStatus.setCharteredPartNo( partNumber );
                                wipStatus.setMesQty(wipStatus.getDieQty());
                                wipStatus.setMesStep(wipStatus.getStep());
                                tsmcFabList.add ( wipStatus );
                            }
                            else
                            {
                                fabLot.setLotId( lotNumber );
                                fabLot.setCustProduct( partNumber );
                                fabLot.setDateIn( wipStatus.getStartDate());
                                fabLot.setQtyIn( quantity +"");
                                fabLot.setStage( wipStatus.getStep() );
                                fabLot.setLotStatus( LOT_STATUS_RUNNING);
                                fabLot.setFabLotNumber(lotNumber);
                                fabLot.setPkgType( wipStatus.getPkg() );
                                fabLot.setForcastedDateOut( wipStatus.getRsDate() );
                            }
                        }
                    }
                }

                /* Fab Option Lots*/
                if( wipStatus.getMfgArea() != null && ("POST_OPTION".equalsIgnoreCase( wipStatus.getMfgArea().trim() ) || "SORT".equalsIgnoreCase( wipStatus.getMfgArea().trim())
                         ) )
                {
                    String vendorName = null;

                    if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("Cypress Fab 2") )
                    {
                        vendorName = VENDOR_NAME_CMT;
                    }
                    else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("Cypress Fab 4") )
                    {
                        vendorName = VENDOR_NAME_CMI;
                    }
                    /*else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CSM") )
                    {
                        vendorName = VENDOR_NAME_CHARTERED;
                    }
                    else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("TSMC") )
                    {
                        vendorName = VENDOR_NAME_TSMC;
                    }*/

                    if( partNumber != null && lotNumber != null && vendorName != null )
                    {
                        fabLot = ( FabSortLot) m_fabOptionDataMap.get( lotNumber + partNumber + vendorName );

                        if( fabLot == null )
                        {
                            fabLot = new FabSortLot( vendorName, LOCATION_TYPE_FAB_OPTION );
                            m_fabOptionDataMap.put( lotNumber + partNumber + vendorName, fabLot );
                        }

                        int quantity = 0;
                        if( fabLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(fabLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch( NumberFormatException npe )
                            {
                            }
                        }
                        if( quantity > 0 && quantity <= 25)
                        {
                            wipStatus.setPsType( LOCATION_TYPE_FAB_OPTION );
                            if ( VENDOR_NAME_CHARTERED.equalsIgnoreCase( vendorName ) )
                            {
                                wipStatus.setCharteredPartNo( partNumber );
                                wipStatus.setMesQty(wipStatus.getDieQty());
                                wipStatus.setMesStep(wipStatus.getStep());
                                charteredFabList.add( wipStatus );
                            }
                            else if ( VENDOR_NAME_TSMC.equalsIgnoreCase( vendorName ) )
                            {
                                wipStatus.setCharteredPartNo( partNumber );
                                wipStatus.setMesQty(wipStatus.getDieQty());
                                wipStatus.setMesStep(wipStatus.getStep());
                                tsmcFabList.add ( wipStatus );
                            }
                            else
                            {
                                fabLot.setLotId( lotNumber );
                                fabLot.setCustProduct( partNumber );
                                fabLot.setDateIn( wipStatus.getStartDate());
                                fabLot.setQtyIn( quantity +"");
                                fabLot.setStage( wipStatus.getStep() );
                                fabLot.setLotStatus( LOT_STATUS_RUNNING);
                                fabLot.setFabLotNumber(lotNumber);
                                fabLot.setPkgType( wipStatus.getPkg() );
                                fabLot.setForcastedDateOut(  wipStatus.getRsDate() );
                            }
                        }
                    }
                }

                /* Wafer Store Lots*/
                /*
                if ( wipStatus.getMfgArea() != null && "WAFERSTORE".equalsIgnoreCase( wipStatus.getMfgArea() ) )
                {
                    String vendorName = null;
                    if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("Cypress Fab 2") )
                    {
                        vendorName = VENDOR_NAME_CMT;
                    }
                    else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("Cypress Fab 4") )
                    {
                        vendorName = VENDOR_NAME_CMI;
                    }
                    else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CSM") )
                    {
                        vendorName = VENDOR_NAME_CHARTERED;
                    }
                    else if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("TSMC") )
                    {
                        vendorName = VENDOR_NAME_TSMC;
                    }

                    if ( partNumber != null && lotNumber != null && vendorName != null )
                    {
                        inventoryLot = ( InventoryLot) m_waferStoreDataMap.get( lotNumber + partNumber + vendorName );
                        if( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot( vendorName, LOCATION_TYPE_WAFER_STORE );
                            m_waferStoreDataMap.put( lotNumber + partNumber + vendorName, inventoryLot );
                        }

                        int quantity = 0;
                        if( inventoryLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(inventoryLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty());
                            }
                            catch( NumberFormatException npe )
                            {
                            }
                        }
						if ( quantity > 0 )
						{
							inventoryLot.setLotNumber( lotNumber );
							inventoryLot.setPartNumber( partNumber );
							inventoryLot.setDateIn( wipStatus.getStartDate());
							inventoryLot.setWaferQtyIn( quantity +"");
							inventoryLot.setStatus(LOT_STATUS_RUNNING );
							inventoryLot.setStage( wipStatus.getStep() );
                            inventoryLot.setFabLotNumber( lotNumber );
                            inventoryLot.setPkgType( wipStatus.getPkg() );
                            inventoryLot.setLotCategory(LOT_CATEGORY_TYPE_PROD);
                        }
                    }
                }*/

                /* Die Bank Lots*/
                if ( wipStatus.getMfgArea() != null && "DIE".equalsIgnoreCase( wipStatus.getMfgArea() ) && !"INTRANS".equalsIgnoreCase( wipStatus.getStep()))
                {
                    String vendorName = null;
                    if( wipStatus.getMfgLoc() != null && "OSE - Taiwan".equalsIgnoreCase( wipStatus.getMfgLoc().trim() ) )
                    {
                        vendorName = VENDOR_NAME_OSET;
                    }
                    else if( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CML") )
                    {
                        vendorName = VENDOR_NAME_CML;
                    }
                    else if( wipStatus.getMfgLoc() != null && "AMKOR-ASI-K1".equalsIgnoreCase( wipStatus.getMfgLoc().trim() ) )
                    {
                        vendorName = VENDOR_NAME_ATK;
                    }
                    else if( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("Texas (CTI)") )
                    {
                        vendorName = VENDOR_NAME_CMT;
                    }

                    if ( partNumber != null && lotNumber != null && vendorName != null )
                    {
                        inventoryLot = ( InventoryLot) m_dieBankDataMap.get( lotNumber + partNumber + vendorName );
                        if( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot( vendorName, INVENTORY_TYPE_DIE_BANK );
                            m_dieBankDataMap.put( lotNumber + partNumber + vendorName, inventoryLot );
                        }

                        int quantity = 0;
                        if( inventoryLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(inventoryLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty());
                            }
                            catch( NumberFormatException npe )
                            {
                            }
                        }
						if ( quantity > 0 )
						{
							inventoryLot.setLotNumber( lotNumber );
							inventoryLot.setPartNumber( partNumber );
							inventoryLot.setDateIn( wipStatus.getStartDate());
							inventoryLot.setQtyIn( quantity +"");
							inventoryLot.setStatus(LOT_STATUS_RUNNING );
							inventoryLot.setStage( wipStatus.getStep() );
                            inventoryLot.setFabLotNumber(lotNumber);
                            inventoryLot.setPkgType( wipStatus.getPkg() );
                            inventoryLot.setExpectedDate(  wipStatus.getRsDate()  );
                        }
                    }
                }

               /*Assembly Lots*/
                if( wipStatus.getMfgArea() != null && "ASSY".equalsIgnoreCase( wipStatus.getMfgArea())
                        && mktPartNumber != null && mktPartNumber.trim().length() > 0 && !"INTRANS".equalsIgnoreCase( wipStatus.getStep()  ) )
                {
                    partNumber = NewAdaptorDAO.getPartNumber( mktPartNumber, WIP_TYPE_ASSEMBLY, WIP_TYPE_ASSEMBLY );

                    if ( partNumber == null)
                    {
                        partNumber = mktPartNumber;
                    }

                    String vendorName = null;
                    if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CML") )
                    {
                        vendorName = VENDOR_NAME_CML;
                    }
                    else if( wipStatus.getMfgLoc() != null && "OSE - Taiwan".equalsIgnoreCase( wipStatus.getMfgLoc().trim() ) )
                    {  
                        vendorName = VENDOR_NAME_OSET;
                    }
                    else if( wipStatus.getMfgLoc() != null && "AMKOR-ASI-K1".equalsIgnoreCase( wipStatus.getMfgLoc().trim() ) )
                    {
                        vendorName = VENDOR_NAME_ATK;
                    }
                    
                    if ( partNumber != null && lotNumber != null && vendorName != null )
                    {
                        assemblyLot = (AssemblyLot)m_assemblyDataMap.get( lotNumber + partNumber + vendorName );
                        if( assemblyLot == null )
                        {
                            assemblyLot = new AssemblyLot();
                            m_assemblyDataMap.put( lotNumber + partNumber + vendorName, assemblyLot );
                        }

                        int quantity = 0;
                        if ( assemblyLot.getQtyIn() != null)
                        {
                            try
                            {
                                quantity = Integer.parseInt(assemblyLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt(wipStatus.getDieQty());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }

                        if( quantity > 0 )
                        {
                            if( VENDOR_NAME_OSET.equalsIgnoreCase( vendorName ) )
                            {
                                wipStatus.setDevice(partNumber);
                                wipStatus.setMesQty(wipStatus.getDieQty());
                                wipStatus.setMesStep(wipStatus.getStep());
                                osetAsssemblyList.add(wipStatus);
                            }
                            else
                            {
                                assemblyLot.setLotNumber( lotNumber );
                                assemblyLot.setDeviceName( partNumber );
                                assemblyLot.setDateIn( wipStatus.getStartDate() );
                                assemblyLot.setQtyIn( quantity +"");
                                assemblyLot.setStage( wipStatus.getStep() );
                                assemblyLot.setVendorName( vendorName );
                                assemblyLot.setStatus( LOT_STATUS_RUNNING);
                                assemblyLot.setFabLotNumber( lotNumber );
                                assemblyLot.setPackageType( wipStatus.getPkg() );
                                assemblyLot.setExpectedDateOut(  wipStatus.getRsDate() );
                            }
                        }
                    }
               }
                /*Test Lots*/
                if( wipStatus.getMfgArea() != null && "TEST".equalsIgnoreCase( wipStatus.getMfgArea())
                        && mktPartNumber != null && mktPartNumber.trim().length() > 0 && !"INTRANS".equalsIgnoreCase( wipStatus.getStep() ) )
                {
                    partNumber = NewAdaptorDAO.getPartNumber( mktPartNumber, LOCATION_TYPE_FT , LOCATION_TYPE_TEST );

                    if ( partNumber == null)
                    {
                        partNumber = mktPartNumber;
                    }

                    String vendorName = null;
                    if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CML") )
                    {
                        vendorName = VENDOR_NAME_CML;
                    }
                    else if( wipStatus.getMfgLoc() != null && "OSE - Taiwan".equalsIgnoreCase( wipStatus.getMfgLoc().trim() ) )
                    {
                        vendorName = VENDOR_NAME_OSET;
                    }
                    
                    if( partNumber != null && lotNumber != null && vendorName != null  )
                    {
                        testLot = (TestLot) m_ftDataMap.get(lotNumber + partNumber + vendorName );

                        if (testLot == null)
                        {
                            testLot = new TestLot();
                            m_ftDataMap.put(lotNumber + partNumber + vendorName, testLot);
                        }

                        int quantity = 0;
                        if (testLot.getQtyIn() != null)
                        {
                            try
                            {
                                quantity = Integer.parseInt(testLot.getQtyIn());
                            }
                            catch (NumberFormatException npe) {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe) {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt(wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe) {
                            }
                        }
						if ( quantity > 0 )
						{
							testLot.setLotNumber(lotNumber);
							testLot.setPartNumber(partNumber);
							testLot.setDateIn(wipStatus.getStartDate());
							testLot.setQtyIn( quantity+"");
							testLot.setStage(wipStatus.getStep() );
							testLot.setVendorName(vendorName);
							testLot.setStatus( LOT_STATUS_RUNNING );
							testLot.setPsType( LOCATION_TYPE_FT );
                            testLot.setFabLotNumber( lotNumber );
                            testLot.setPackageType( wipStatus.getPkg() );
                            testLot.setExpecetedDate(  wipStatus.getRsDate() );
                        }
                    }
                }

                /*FPO Lots For FPO Process*/
                if( wipStatus.getMfgArea() != null && "MARK".equalsIgnoreCase( wipStatus.getMfgArea() )
                        && mktPartNumber != null && mktPartNumber.trim().length() > 0 && !"INTRANS".equalsIgnoreCase( wipStatus.getStep() ) )
                {

                    partNumber = NewAdaptorDAO.getPartNumber( mktPartNumber, LOCATION_TYPE_FPO , LOCATION_TYPE_TEST );

                    if ( partNumber == null)
                    {
                        partNumber = mktPartNumber;
                    }

                    String vendorName = null;
                    if ( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CML") )
                    {
                        vendorName = VENDOR_NAME_CML;
                    }

                    if( partNumber != null && lotNumber != null && vendorName != null )
                    {

                        testLot = ( TestLot) m_fpoDataMap.get( lotNumber + partNumber );

                        if( testLot == null )
                        {
                            testLot = new TestLot();
                            m_fpoDataMap.put( lotNumber + partNumber, testLot );
                        }

                        int quantity = 0;
                        if( testLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(testLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch( NumberFormatException npe )
                            {
                            }
                        }

						 if ( quantity > 0 )
						 {

							testLot.setLotNumber( lotNumber );
							testLot.setPartNumber( partNumber );
							testLot.setDateIn( wipStatus.getStartDate());
							testLot.setQtyIn( quantity +"");
							testLot.setStatus(LOT_STATUS_RUNNING);
							testLot.setVendorName( vendorName );
							testLot.setStage( wipStatus.getStep() );
							testLot.setPsType(LOCATION_TYPE_FPO );
                            testLot.setFabLotNumber( lotNumber );
                            testLot.setPackageType( wipStatus.getPkg() );
                            testLot.setExpecetedDate(  wipStatus.getRsDate() );
                         }
                    }

                }
                /*TR Lots*/
                if( wipStatus.getMfgArea() != null && "TR".equalsIgnoreCase( wipStatus.getMfgArea())
                        && mktPartNumber != null && mktPartNumber.trim().length() > 0 && !"INTRANS".equalsIgnoreCase( wipStatus.getStep() ) )
                {
                    partNumber = NewAdaptorDAO.getPartNumber( mktPartNumber, LOCATION_TYPE_TAPE_REEL, LOCATION_TYPE_CLASS_STORE);

                    if ( partNumber == null)
                    {
                        partNumber = mktPartNumber;
                    }

                    String vendorName = null;
                    if( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CML") )
                    {
                        vendorName = VENDOR_NAME_CML;
                    }

                    if( partNumber != null && lotNumber != null && vendorName != null )
                    {

                        inventoryLot = ( InventoryLot) m_trDataMap.get( lotNumber + partNumber );
                        if( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot( vendorName, LOCATION_TYPE_TAPE_REEL );
                            m_trDataMap.put( lotNumber + partNumber, inventoryLot );
                        }

                        int quantity = 0;
                        if( inventoryLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(inventoryLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch( NumberFormatException npe )
                            {
                            }
                        }

						if ( quantity > 0 )
						{
							inventoryLot.setLotNumber( lotNumber );
							inventoryLot.setPartNumber( partNumber );
							inventoryLot.setDateIn( wipStatus.getStartDate());
							inventoryLot.setQtyIn( quantity +"");
							inventoryLot.setStatus(LOT_STATUS_RUNNING);
							inventoryLot.setStage( wipStatus.getStep() );
							inventoryLot.setFabLotNumber(lotNumber);
                            inventoryLot.setPkgType( wipStatus.getPkg() );
                            inventoryLot.setExpectedDate(  wipStatus.getRsDate() );
                        }
                    }

                }
                /*FG Lots*/
                if( wipStatus.getMfgArea() != null && "FG".equalsIgnoreCase( wipStatus.getMfgArea() )
                        && mktPartNumber != null && mktPartNumber.trim().length() > 0 && !"INTRANS".equalsIgnoreCase( wipStatus.getStep() ) )
                {
                     String vendorName = null;
                    if( wipStatus.getMfgLoc() != null && wipStatus.getMfgLoc().trim().startsWith("CML") )
                    {
                        vendorName = VENDOR_NAME_CML;
                    }

                    if ( mktPartNumber != null && lotNumber != null && vendorName != null )
                    {
                        inventoryLot = ( InventoryLot) m_fgDataMap.get( lotNumber + mktPartNumber );

                        if( inventoryLot == null )
                        {
                            inventoryLot = new InventoryLot( vendorName, LOCATION_TYPE_FG );
                            m_fgDataMap.put( lotNumber + mktPartNumber, inventoryLot );
                        }

                        int quantity = 0;
                        if( inventoryLot.getQtyIn() != null )
                        {
                            try
                            {
                                quantity = Integer.parseInt(inventoryLot.getQtyIn());
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                            try
                            {
                                quantity += Integer.parseInt( wipStatus.getDieQty() );
                            }
                            catch (NumberFormatException npe)
                            {
                            }
                        }
                        else
                        {
                            try
                            {
                                quantity = Integer.parseInt( wipStatus.getDieQty());
                            }
                            catch( NumberFormatException npe )
                            {
                            }
                        }

						if ( quantity > 0 )
						{
							inventoryLot.setLotNumber( lotNumber );
							inventoryLot.setPartNumber( mktPartNumber );
							inventoryLot.setDateIn( wipStatus.getStartDate());
							inventoryLot.setQtyIn( quantity +"");
							inventoryLot.setStatus(LOT_STATUS_RUNNING);
							inventoryLot.setStage( wipStatus.getStep() );
							inventoryLot.setFabLotNumber(lotNumber);
                            inventoryLot.setPkgType( wipStatus.getPkg() );
                            inventoryLot.setExpectedDate(  wipStatus.getRsDate() );
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log("ERROR!ERROR! While parsing the SLI Wip Fed Details" + e);
            System.out.println("ERROR!ERROR! While parsing the SLI Wip Fed Details" + e);
            throw e;
        }
    }


    private void parseDailyWipReport( String fileName ) throws Exception
   	{
   		if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result     = null;
        FabSortLot fabSortLot   = null;
        String lotNumber        = null;
        String partNumber       = null;
        String spiltNo          = null;
        try
        {
            File fabWipFile = new File( fileName );
            if ( fabWipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for Fab Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Fab Wip Report..." );
            Parser parser = ParserFactory.getCSVParser( fabWipFile, ',' );

            ((CSVParserImpl)parser).setHeaderRowIdx(0);
            ((CSVParserImpl)parser).setDataStartRowIdx(1);

            result = parser.parse();

            while ( result.next() )
            {
                partNumber = result.getString("device");
                lotNumber  = result.getString("lot");
                spiltNo    = result.getString("split");
                String fabLotNumber = null;
                if( lotNumber != null && lotNumber.trim().length() > 0 && spiltNo != null && spiltNo.trim().length() > 0 )
                {
                    fabLotNumber = lotNumber + "-" + spiltNo;
                }
                else
                {
                    fabLotNumber = lotNumber;
                }

                if ( partNumber != null && partNumber.trim().length() > 0 && fabLotNumber != null && fabLotNumber.trim().length() > 0 )
                {
                     fabSortLot = ( FabSortLot ) m_fabDataMap.get( partNumber + fabLotNumber );
                     if ( fabSortLot == null )
                     {
                         fabSortLot = new FabSortLot( VENDOR_NAME_CMI, WIP_TYPE_FAB );
                         m_fabDataMap.put( partNumber + fabLotNumber , fabSortLot );
                     }

                     int quantity = 0;

                     if( fabSortLot.getQtyIn() != null )
                     {
                         try
                         {
                             quantity = Integer.parseInt( fabSortLot.getQtyIn() );
                         }
                         catch ( NumberFormatException ignore )
                         {
                         }
                         try
                         {
                             quantity += result.getInt("curr_wfr_qty");
                         }
                         catch ( NumberFormatException ignore )
                         {
                         }
                     }
                     else
                     {
                         try
                         {
                             quantity = result.getInt("curr_wfr_qty");
                         }
                         catch ( NumberFormatException ignore )
                         {
                         }
                     }
                     if ( quantity > 0 )
                     {
                         fabSortLot.setLotId( fabLotNumber );
                         fabSortLot.setCustProduct( partNumber );
                         fabSortLot.setFabLotNumber( fabLotNumber );
                         fabSortLot.setDateIn( StringUtils.formatDateToString(new Date(), "MM/dd/yyyy HH:mm:ss") );
                         fabSortLot.setQtyIn( quantity +"");
                         fabSortLot.setStage( result.getString("step") );
                         fabSortLot.setStagePosition( result.getString("loc") );
                         fabSortLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );

                         fabSortLot.setShip_fcst_date( result.getString("rs_date") );
                         fabSortLot.setOutLookDate( result.getString("rs_date") );
                         fabSortLot.setFabId( result.getString("fab_loc") );
                         fabSortLot.setLotStatus( LOT_STATUS_RUNNING );
                     }
                }

            }
        }
        catch ( Exception ex )
        {   System.out.println("ERROR!!!ERROR!!! While Parsing the FAB4(CMI) Daily wip Sheet");
            ex.printStackTrace();
            throw ex;
        }

    }
    private void getShippingDetails(ArrayList shippingDataList) throws Exception
    {
       if ( shippingDataList == null || shippingDataList.size() == 0 )
       {
            return;
       }
       WipFedStatus shipStatus  = null;
       String partNumber                = null;
       ShippedLot shippedLot          = null;
       String fabLotNumber              = null;
       String nextLocation              = null;
       try
       {
           Iterator iterator = shippingDataList.iterator();

           while ( iterator.hasNext() )
           {
               shipStatus = (WipFedStatus) iterator.next();

               partNumber   = shipStatus.getDevice();
               fabLotNumber = shipStatus.getLotNumber();
               nextLocation = shipStatus.getNextMfgLoc();
               String shipDate = shipStatus.getShipDate();

               if ( partNumber != null && fabLotNumber != null )
               {
                   shippedLot = ( ShippedLot ) m_fabShipDataMap.get ( partNumber +  fabLotNumber + nextLocation + shipDate );

                   if ( shippedLot == null )
                   {
                        shippedLot = new ShippedLot(null, LOCATION_TYPE_FAB);
                        m_fabShipDataMap.put( partNumber + fabLotNumber + nextLocation + shipDate, shippedLot );
                   }

                   int quantity = 0;
                   String waferId   = null;
                   if ( shippedLot.getShipQty() != null )
                   {
                       waferId = shippedLot.getWaferID() + shipStatus.getWaferID() + ";";
                       try
                       {
                           quantity = Integer.parseInt( shippedLot.getShipQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                       try
                       {
                           quantity += Integer.parseInt( shipStatus.getShipQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                   }
                   else
                   {
                       waferId = shipStatus.getWaferID() + ";";
                       try
                       {
                           quantity = Integer.parseInt( shipStatus.getShipQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                   }

                   if ( quantity > 0 )
                   {
                       shippedLot.setLotNumber( fabLotNumber );
                       shippedLot.setPartNumber( partNumber );
                       shippedLot.setShipDate( shipDate );
                       shippedLot.setShipQty( quantity + "" );
                       shippedLot.setNextLocation( nextLocation );
                       shippedLot.setFabLotNumber( fabLotNumber );
                       shippedLot.setWaferID( waferId );

                   }
               }
           }
        }
        catch(Exception e )
        {
            e.printStackTrace();
            log("Exception while geting CML Shipping inforamtion" + e);
            throw  e;
        }
    }

    private void log(String message)
    {
        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
